package bs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import bs.entity.User;

/**
 * 登录、权限验证过滤器
 * PermissionFilter:
 *
 * @author 姜治昊
 * @time 2017年11月20日 上午11:22:55
 */
public class PermissionFilter implements Filter {
	
	private static String[] ALLOW_REQUEST = null;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String param = config.getInitParameter("ALLOW_REQUEST");
		ALLOW_REQUEST = param.split("-");
	}

	/**
	 * 主逻辑代码
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) req;
		String url = request.getRequestURI().toString();
		if(notNeedLogin(url, request)) {
			chain.doFilter(req, resp);
		} else {
			//需要登录
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("LOGIN_USER");
			if(null == user) {
				//未登录
				//记录请求URL， 跳转至登录界面
				session.setAttribute("REQUEST_URL_BEFORE_LOGIN", url);
				request.getRequestDispatcher("/views/door/login.jsp").forward(req, resp);
			} else {
				//已经登录
				//判断是否有权限
				if(hasPermission(url, session)) {
					chain.doFilter(req, resp);
				} else {
					//跳转到权限不足界面
					request.getRequestDispatcher("/views/error/permission_denied.jsp").forward(req, resp);
				}
			}
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 工具方法：验证跳转界面是否需要登录
	 * @param toUrl
	 * @param request
	 * @return
	 */
	private boolean notNeedLogin(String toUrl,HttpServletRequest request) {
		for(String url : ALLOW_REQUEST) {
			if(toUrl != null && toUrl.indexOf(url) >= 0) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断是否有权限
	 * @param url
	 * @param session
	 * @return
	 */
	public boolean hasPermission(String url, HttpSession session) {
		String[] urls = (String[]) session.getAttribute("PERMISSION_URLS");
		for(String u : urls) {
			if(url.indexOf(u) >= 0) {
				return true;
			}
		}
		return false;
	}
	
}
